package com.caishi.lkx.common;

import com.zzw.common.exception.BizException;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;

import java.util.Map;
@Slf4j
public class Jwt {

    /**
     * 秘钥
     */
    private static final byte[] SECRET = "d00874aaef1242e9b4f8c3fad453243v".getBytes();

    /**
     * 初始化head部分的数据为
     * {
     * "alg":"HS256",
     * "type":"JWT"
     * }
     */
    private static final JWSHeader header = new JWSHeader(JWSAlgorithm.HS256, JOSEObjectType.JWT, null, null, null,
            null, null, null, null, null, null, null, null);

    public static String createToken(Map<String, Object> payload) {
        String tokenString = null;
        JWSObject jwsObject = new JWSObject(header, new Payload(new JSONObject(payload)));
        try {
            jwsObject.sign(new MACSigner(SECRET));
            tokenString = jwsObject.serialize();
        } catch (JOSEException e) {

        }
        return tokenString;
    }

    /**
     * 校验token是否合法，返回Map集合,集合中主要包含    state状态码   data鉴权成功后从token中提取的数据
     * 该方法在过滤器中调用，每次请求API时都校验
     *
     * @param token
     * @return Map<String, Object>
     */
    public static Map<String, Object> validToken(String token) throws BizException {
        try {
            JWSObject jwsObject = JWSObject.parse(token);
            JWSVerifier verifier = new MACVerifier(SECRET);
            if (jwsObject.verify(verifier)) {
                Payload payload = jwsObject.getPayload();
                return payload.toJSONObject();
            }
        } catch (Exception e) {
            log.error("token校验异常", e);
        }
        throw new BizException(AclResultCode.authFail);
    }

}
